<?php
  class Geocode {

    function from_zipcode($zipcode, $country) {
      global $cms;

      if(!$country)
        $country = "Nederland";
      $sql = "select * from geodata.google_geocode_cache where zipcode='$zipcode' and country='$country'";
      $result = $cms->db->query($sql);
      if($result && $result->num_rows)
        return($result->get_firstrow());
      else {
        $addr = urlencode(iconv("utf-8","ascii//TRANSLIT",$zipcode.','.$country));
        $url = 'http://maps.googleapis.com/maps/api/geocode/json?address='.$addr.'&sensor=false';
        $response_str = file_get_contents($url);
        $response = json_decode($response_str);
        if($response->status == "OK") {
          $values['zipcode']      = $zipcode;
          foreach($response->results[0]->address_components as $address_component) {
            switch($address_component->types[0]) {
              case 'route':
                $values['street'] = $address_component->long_name;
                break;
              case 'locality':
                $values['city'] = $address_component->long_name;
                break;
              case 'administrative_area_level_2':
                $values['municipality'] = $address_component->long_name;
                break;
              case 'administrative_area_level_1':
                $values['province'] = $address_component->long_name;
                break;
            }
          }
          $values['country']      = $country;
          $values['lat']          = $response->results[0]->geometry->location->lat;
          $values['lng']          = $response->results[0]->geometry->location->lng;
          if(!$values['street'] && $values['lat'] && $values['lng']) {
            // Strangely we don't get the streetname using this API
            $latlng = $values['lat'].','.$values['lng'];
            $url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.$latlng.'&sensor=false';
            $response_str = file_get_contents($url);
            $response = json_decode($response_str);
            if($response->status == "OK") {
              foreach($response->results[0]->address_components as $address_component) {
                if($address_component->types[0] == 'route')
                    $values['street'] = $address_component->long_name;
              }
            }
          }
          // Only store if data is complete. Otherwise we'll try later again
          if($values['city'] && $values['street'] && $values['lat'] && $values['lng'])
            $cms->db->update_tuple_array($values, 'geodata.google_geocode_cache', 'zip_data');
          return $values;
        }
        else {
          return false;
          // "$response->status : $addr not found<br>";
        }
      }
    }

  }
?>
